package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.CardBin;
import com.cardbaobao.cardbabyclient.model.result.CardBinResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.IdCardValidator;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/4 13:45.
 * 身份验证
 */

public class IdentifyVerifyActivity extends BaseActivity {
    public static final String NAME_S ="name";//姓名
    public static final String ID_CARD_NO_S ="idCardNo";//身份证号码
    public static final String CARD_NUMBER_S="cardNumber";//银行卡号码
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.et_id_no)
    EditText etIdNo;
    @BindView(R.id.et_bank_card_no)
    EditText etBankCardNo;
    @BindView(R.id.bt_next_step)
    Button btNextStep;

    private int activityFrom;

    private String name;
    private String idCardNo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_identify_verify;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).keyboardEnable(true).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Intent intent=getIntent();
        boolean enable=true;
        String name=intent.getStringExtra(NAME_S);
        if(!TextUtils.isEmpty(name)) {
            IdentifyVerifyActivity.this.name = name;
            //姓名进行*处理
            StringBuilder sb = new StringBuilder();
            for (int i = 0, length = name.length(); i < length; i++) {
                if (i == length - 1) {
                    sb.append(name.substring(i, i + 1));
                } else {
                    sb.append("*");
                }
            }
            etRealName.setText(sb.toString());
            etRealName.setEnabled(false);
        }else{
            enable=false;
        }
        etRealName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBtStatus();
                IdentifyVerifyActivity.this.name=s.toString().trim();
            }
        });
        final String idCardNo=intent.getStringExtra(ID_CARD_NO_S);
        if(!TextUtils.isEmpty(idCardNo)){
            IdentifyVerifyActivity.this.idCardNo=idCardNo;
            //身份证进行*处理
            StringBuilder sb=new StringBuilder();
            for (int i = 0, length = idCardNo.length(); i < length; i++) {
                if (i == length - 8 || i == length - 7 || i == length - 6 || i == length - 5) {
                    sb.append("*");
                } else {
                    sb.append(idCardNo.charAt(i));
                }
            }
            etIdNo.setText(sb.toString());
            etIdNo.setEnabled(false);
        }else{
            enable=false;
        }
        etIdNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBtStatus();
                IdentifyVerifyActivity.this.idCardNo=s.toString().trim();
            }
        });
        String cardNumber=intent.getStringExtra(CARD_NUMBER_S);
        if(!TextUtils.isEmpty(cardNumber)){
            etBankCardNo.setText(cardNumber);
        }else{
            enable=false;
        }

        activityFrom=intent.getIntExtra(BankCardVerifyActivity.PAGE_FROM_I,
                0);
        btNextStep.setEnabled(enable);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mCurrentPageId=Self.Page.app_identity_vcertification_addcard;
        initIntent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName("添加储蓄卡-身份验证");
    }

    //验证姓名
    private boolean checkName(){
        boolean result=true;
        if(TextUtils.isEmpty(name)){
            result=false;
            ToastUtil.showToast("请输入姓名");
        } else if(name.length()<2){
            result=false;
            ToastUtil.showToast("姓名格式不正确，请重新输入");
        }
        return result;
    }

    //验证身份证
    private boolean checkIdCardNo(){
        boolean result=true;
        if(TextUtils.isEmpty(idCardNo)){
            result=false;
            ToastUtil.showToast("请输入身份证号码");
        }else{
            IdCardValidator validator=new IdCardValidator();
            if(!validator.isValidate18Idcard(idCardNo)){
                result=false;
                ToastUtil.showToast("身份证格式错误，请重新输入");
            }
        }
        return result;
    }

    //验证银行卡号
    private boolean checkCardNumber(){
        String cardNumber=etBankCardNo.getText().toString().trim();
        boolean result=true;
        if(!RegularUtil.checkBankCard(cardNumber)){
            result=false;
            ToastUtil.showToast("请输入正确的银行卡号");
        }
        return result;
    }

    @OnTextChanged(R.id.et_bank_card_no)
    public void afterBankCardNoChange(Editable s){
        setBtStatus();
    }

    private void setBtStatus(){
        if(etRealName.getText().toString().trim().length()>0&&
                etIdNo.getText().toString().trim().length()>0&&
                etBankCardNo.getText().toString().trim().length()>0){
            btNextStep.setEnabled(true);
        }else{
            btNextStep.setEnabled(false);
        }
    }

    private void queryCardBin(String cardNumber){
        showProgressDialog(false);
        Api.queryCardBin(cardNumber).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                CardBinResult result= JsonUtil.json2Object(s,CardBinResult.class);
                if(result.getCode()== Constant.SUC_CODE){
                    //成功
                    CardBin bin=result.getData();
                    if("1".equals(bin.getBank_type())){
                        //储蓄卡
                        mIntent.setClass(mContext,BankCardVerifyActivity.class);
                        mIntent.putExtra(BankCardVerifyActivity.PAGE_FROM_I,
                                activityFrom);
                        mIntent.putExtra(NAME_S,name);
                        mIntent.putExtra(ID_CARD_NO_S,idCardNo);
                        mIntent.putExtra(CARD_NUMBER_S,etBankCardNo.getText().toString().trim());
                        mIntent.putExtra(BankCardVerifyActivity.CARD_NAME_S,bin.getBank_name());
                        mIntent.putExtra(BankCardVerifyActivity.CARD_ID_S,bin.getBank_id());
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                        finish();
                    }else{
                        ToastUtil.showToast("请输入储蓄卡卡号");
                    }
                }else{
                    ToastUtil.showToast(result.getMsg());
                }
            }
        });
    }

    @OnClick(R.id.bt_next_step)
    public void onClick(View view){
        switch (view.getId()){
            case R.id.bt_next_step:
                //埋点
                SelfUtils.buriedClickData(Self.Action.app_click_identity_vcertification_addcard_nextstep,
                        Self.Action.app_click_identity_vcertification_addcard_nextstep_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                if(checkName()&&checkIdCardNo()&&checkCardNumber()){
                    queryCardBin(etBankCardNo.getText().toString().trim());
                }
                break;
        }
    }
}
